package com.tanhua.management.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.management.exception.BusinessException;
import com.tanhua.management.mapper.UserFreezeMapper;
import com.tanhua.management.pojo.UserFreeze;
import com.tanhua.management.vo.UserFreezeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;


/**
 * @author XDY
 * @date 2020/12/24
 */
@Service
public class UserFreezeService {

    private static final String CACHE_KEY_FREEZE_PREFIX = "FREEZE_";

    @Autowired
    private UserFreezeMapper userFreezeMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 冻结
     *
     * @param userFreezeVo
     * @return
     */
    public Boolean freeze(UserFreezeVo userFreezeVo) {

        // 判断用户id是否存在
        if (ObjectUtil.isEmpty(userFreezeVo.getUserId())) {
            throw new BusinessException("用户id不能为空！");
        }
        // 判断状态是否已被冻结
        // 创建查询条件构建器
        QueryWrapper<UserFreeze> queryWrapper = new QueryWrapper<>();
        // 设置条件
        queryWrapper.eq("user_id", userFreezeVo.getUserId());
        UserFreeze oneUserFreeze = this.userFreezeMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(oneUserFreeze)) {
            throw new BusinessException("用户已被冻结！");
        }

        // 转换对象
        UserFreeze userFreeze = BeanUtil.toBean(userFreezeVo, UserFreeze.class);
        this.userFreezeMapper.insert(userFreeze);

        // 冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
        int days = 0;
        if (userFreezeVo.getFreezingTime() == 1) {
            days = 3;
        } else if (userFreezeVo.getFreezingTime() == 2) {
            days = 7;
        }

        // 存入redis
        String cacheKey = CACHE_KEY_FREEZE_PREFIX + userFreezeVo.getUserId();
        if (days > 0) {
            this.redisTemplate.opsForValue().set(cacheKey, "ok", Duration.ofDays(days));
        } else {
            this.redisTemplate.opsForValue().set(cacheKey, "ok");
        }
        return true;
    }

    /**
     * 解冻
     * @param userFreezeVo
     * @return
     */
    public Boolean unfreeze(UserFreezeVo userFreezeVo) {
        String cacheKey = CACHE_KEY_FREEZE_PREFIX + userFreezeVo.getUserId();

        try {
            userFreezeMapper.delete(new QueryWrapper<UserFreeze>().eq("user_id", userFreezeVo.getUserId()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this.redisTemplate.delete(cacheKey);
    }

    /**
     * 查询冻结范围
     * @param userId
     * @return
     */
    public Integer queryFreezingRange(String userId) {
        try {
            String cacheKey = CACHE_KEY_FREEZE_PREFIX + userId;
            String state = this.redisTemplate.opsForValue().get(cacheKey);
            if (StringUtils.isNotEmpty(state)){

                // 创建查询条件构建器
                QueryWrapper<UserFreeze> queryWrapper = new QueryWrapper<>();
                // 设置条件
                queryWrapper.eq("user_id", userId);
                UserFreeze oneUserFreeze = this.userFreezeMapper.selectById(queryWrapper);
                return oneUserFreeze.getFreezingRange();
        }
            userFreezeMapper.delete(new QueryWrapper<UserFreeze>().eq("user_id", userId));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
